<template>
  <view class="container">
    <tui-tabs :tabs="tabs" :isFixed="scrollTop>=0" :currentTab="currentTab" selectedColor="#E41F19" sliderBgColor="#E41F19" @change="change" itemWidth="20%"></tui-tabs>
    <!--选项卡逻辑自己实现即可，此处未做处理-->
    <view :class="{'tui-order-list':scrollTop>=0}">
      <view v-if="list.length!=0">
        <view class="tui-order-item" v-for="(row,index) in list" :key="index">
          <tui-list-cell :hover="false" :lineLeft="false">
            <view class="tui-goods-title">
              <view>订单号：{{ row.orderId }}</view>
              <view class="tui-order-status">{{ orderStatusEnums[row.orderStatus] || '' }}</view>
            </view>
          </tui-list-cell>
          <block v-for="(item,i) in row.items" :key="i">
            <tui-list-cell padding="0" @click="detail(item.productId)">
              <view class="tui-goods-item">
                <image :src="item.productItemPic" class="tui-goods-img"></image>
                <view class="tui-goods-center">
                  <view class="tui-goods-name">{{item.productItemName}}</view>
                  <view class="tui-goods-attr">{{ (item.productItemSpec || []).map(d => d.propertyName).join(', ') }}</view>
                </view>
                <view class="tui-price-right">
                  <view>¥{{item.productItemPrice}}</view>
                  <view>x{{item.productItemNum}}</view>
                </view>
              </view>
            </tui-list-cell>
          </block>
          <tui-list-cell :hover="false" v-if="row.deliveryDTO.deliveryName && row.deliveryDTO.deliveryNo">
            <view class="delivery-name">
              快递公司: {{ row.deliveryDTO.deliveryName || '-' }}
            </view>
            <view class="delivery-no">
              快递单号: {{ row.deliveryDTO.deliveryNo || '-' }}
            </view>
          </tui-list-cell>
          <tui-list-cell :hover="false" unlined>
            <view class="tui-goods-price">
              <view>共{{ row.items.length }}件商品 合计：</view>
              <view class="tui-size-24">￥</view>
              <view class="tui-price-large">{{ row.orderAmount }}</view>
            </view>
          </tui-list-cell>
          <!-- 订单状态按钮
					<view class="tui-order-btn">
						<view class="tui-btn-ml">
							<tui-button type="black" plain width="152rpx" height="56rpx" :size="26" shape="circle">查看发票</tui-button>
						</view>
						<view class="tui-btn-ml">
							<tui-button type="black" plain width="152rpx" height="56rpx" :size="26" shape="circle">评价晒单</tui-button>
						</view>
						<view class="tui-btn-ml">
							<tui-button type="danger" plain width="152rpx" height="56rpx" :size="26" shape="circle">再次购买</tui-button>
						</view>
					</view> -->
          <!-- 订单状态按钮 -->
          <view class="tui-order-btn">
            <!-- <view v-if="row.orderStatus==1" class="tui-btn-ml">
							<tui-button type="black" plain width="152rpx" height="56rpx" :size="26" shape="circle">取消订单</tui-button>
						</view> -->
            <view v-if="row.orderStatus==1" class="tui-btn-ml">
              <tui-button type="danger" @click="handlePay(row)" plain width="152rpx" height="56rpx" :size="26" shape="circle">付款</tui-button>
            </view>
            <view v-if="row.orderStatus==3" class="tui-btn-ml">
              <tui-button type="danger" @click="handleRemaid(row)" plain width="152rpx" height="56rpx" :size="26" shape="circle">提醒发货</tui-button>
            </view>
            <view v-if="row.orderStatus==5" class="tui-btn-ml">
              <tui-button type="danger" @click="handleConfirmGoods(row, index)" plain width="152rpx" height="56rpx" :size="26" shape="circle">确认收货</tui-button>
            </view>
            <view v-if="row.orderStatus==9" class="tui-btn-ml">
              <tui-button type="danger" @click="handleByAgain(row)" plain width="152rpx" height="56rpx" :size="26" shape="circle">再次购买</tui-button>
            </view>
            <view v-if="row.orderStatus==3" class="tui-btn-ml">
              <tui-button type="danger" @click="handleRefund(row, index)" plain width="152rpx" height="56rpx" :size="26" shape="circle">申请退款</tui-button>
            </view>
            <view v-if="[4, 5, 6].includes(row.orderStatus)" class="tui-btn-ml">
              <tui-button type="danger" @click="handleRefund(row, index, true)" plain width="242rpx" height="56rpx" :size="26" shape="circle">申请退款/退货</tui-button>
            </view>
            <view v-if="row.orderStatus === 8" class="tui-btn-ml">
              <tui-button type="danger" @click="handleCancelRefund(row, index)" plain width="152rpx" height="56rpx" :size="26" shape="circle">取消退款</tui-button>
            </view>
            <view v-if="row.orderStatus === 7" class="tui-btn-ml">
              <tui-button type="danger" @click="handleCancelRefund(row, index, true)" plain width="260rpx" height="56rpx" :size="26" shape="circle">取消退款/退货申请</tui-button>
            </view>
          </view>
        </view>
      </view>

      <view class="mt20" v-else>
        <tui-no-data :fixed="false" imgUrl="https://cwmall.oss-cn-shanghai.aliyuncs.com/mp-icon/img_noorder_3x.png">暂无订单</tui-no-data>
      </view>

    </view>

    <!--加载loadding-->
    <view v-if="list.length!=0">
      <tui-loadmore v-if="loadding" :index="3" type="red"></tui-loadmore>
      <tui-nomore v-if="!pullUpOn" backgroundColor="#fafafa"></tui-nomore>
    </view>
    <!--加载loadding-->

    <!-- 联系客服 -->
    <tui-customer></tui-customer>

  </view>
</template>

<script>
import { orderStatusEnums } from "@/constants";

export default {
  data() {
    return {
      orderStatusEnums,
      tabs: [
        {
          name: "全部",
          value: '1,2,3,4,5,6,7,8,10,12',
          index: 0,
        },
        {
          name: "待付款",
          value: 1,
          index: 1,
        },
        {
          name: "待发货",
          value: 3,
          index: 2,
        },
        {
          name: "待收货",
          value: '4,5,6',
          index: 3,
        },
        {
          name: "退款/售后",
          value: '7,8',
          index: 4,
        },
      ],
      currentTab: 0,
      pageIndex: 1,
      loadding: false,
      pullUpOn: true,
      scrollTop: 0,
      orderStatus: "1,2,3,4,5,6,7,8,10,12",
      pageNum: 1,
      list: [],
    };
  },
  onLoad({ status }) {
    this.init(status);
  },
  methods: {
    init(status) {
      if (status) {
        const orderStatus = this.tabs.find((d) => String(d.value) === String(status));
        // console.log(status, orderStatus, this.tabs, 'orderStatus,, orderStatus')
        this.currentTab = orderStatus.index;
        this.orderStatus = orderStatus.value;
      }
      this.GetOrderList();
    },
    // 获取订单列表
    async GetOrderList(callback) {
      const { orderStatus, pageNum } = this.$data;
	  // console.log(String(orderStatus).split(','), 'String(orderStatus).split(',')')
      const response = await this.$api.GetOrderList({
        merchantId: this.$store.state.merchantId,
        customerId: this.$store.state.customerId,
        needTotalCount: true,
        orderStatus,
        pageNum,
        pageSize: 10,
      });

      const list = response.data.map((d) => ({
        ...d,
        items: d.items.map((dd) => ({
          ...dd,
          productItemSpec: JSON.parse(dd.productItemSpec),
        })),
      }));
      this.list = this.list.concat(list);

      // 处理下用户选择的规格的显示 别问我这个数据格式
      // Array.isArray(this.list) && this.list.map(row=>{
      //     Array.isArray(row.items) && row.items.map(goods=>{
      //         try{
      //             let userSelectSpecText = ''
      //             Array.isArray(goods.properties) && goods.properties.map(specs=>{
      //                 Array.isArray(specs.properties) && specs.properties.map(item=>{
      //                     userSelectSpecText += `${item.propertyName} `
      //                 })
      //             })
      //             goods.userSelectSpecText = userSelectSpecText
      //         }catch(err){
      //             console.log(err)
      //         }
      //     })
      // })
      callback && callback(list);
    },
    change(e) {
      const orderStatus = this.tabs.find((d) => d.index === e.index);
      this.currentTab = e.index;
      this.orderStatus = orderStatus.value;

      this.pageNum = 1;
      this.GetOrderList((list) => {
        this.list = list;
      });
    },
    detail(id) {
      uni.navigateTo({
        url: `/pagesB/productDetail/productDetail?productCode=${id}`,
      });
    },
    handlePay(row) {
      console.log(row);
      const _this = this;
      this.$store.dispatch("USER_PAY", {
        orderId: row.orderId,
        success(data) {
          uni.showToast({
            title: "支付成功",
          });
        },
        fail() {
          uni.showToast({
            title: "支付失败",
          });
        },
        callBack() {
          _this.pageNum = 1;
          _this.GetOrderList((list) => {
            _this.list = list;
          });
        },
      });
    },
    // 商品评价
    handleComment(row) {
      // console.log(row)

      let { items } = row;
      let { productCode, productPic } = items[0];

      uni.navigateTo({
        url: `/pagesB/comment/comment?productCode=${productCode}&productPic=${productPic}`,
      });
    },
    async handleRemaid(row) {
      const data = await this.$api.RemindDelivery(row.orderId);
      if (data.success) {
        uni.showToast({
          title: "已提醒发货",
        });
      }
    },
    async handleRefund(row, index, withGoods = false) {
      const that = this;
      uni.showModal({
        title: "温馨提示",
        content: withGoods
          ? "亲～确定要申请退款/退货吗？"
          : "亲～确定要申请退款？",
        success: async function (res) {
          if (res.confirm) {
            const data = await that.$api.RequestRefund(row.orderId);
            if (data.success) {
              row.orderStatus = withGoods ? 7 : 8;
              that.$set(that.list, index, row);
            }
          } else if (res.cancel) {
            console.log("用户点击取消");
          }
        },
      });
    },
    async handleConfirmGoods(row, index) {
      const data = await this.$api.ConfirmGoods(row.orderId);
      if (data.success) {
        row.orderStatus = 9;
        this.$set(this.list, index, row);
      }
    },
    async handleCancelRefund(row, index, withGoods = false) {
      const that = this;
      uni.showModal({
        title: "温馨提示",
        content: withGoods
          ? "亲～确定要取消退款/退货申请？"
          : "亲～确定要取消退款？",
        success: async function (res) {
          if (res.confirm) {
            const data = await that.$api.CancelRefund(row.orderId);
            if (data.success) {
              that.GetOrderList((list) => {
                that.list = list;
              });
            }
          } else if (res.cancel) {
            console.log("用户点击取消");
          }
        },
      });
    },
  },
  onPullDownRefresh() {
    this.pageNum = 1;
    this.GetOrderList((list) => {
      this.list = list;
      uni.stopPullDownRefresh();
    });
  },
  onReachBottom() {
    this.pageNum++;
    this.loadding = true;
    this.pullUpOn = true;
    this.GetOrderList(() => {
      this.loadding = false;
      this.pullUpOn = false;
    });
  },
  onPageScroll(e) {
    this.scrollTop = e.scrollTop;
  },
};
</script>

<style>
.container {
  padding-bottom: env(safe-area-inset-bottom);
}

.tui-order-list {
  margin-top: 80rpx;
}

.tui-order-item {
  margin-top: 20rpx;
  border-radius: 10rpx;
  overflow: hidden;
}

.tui-goods-title {
  width: 100%;
  font-size: 28rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.tui-order-status {
  color: #888;
  font-size: 26rpx;
}

.tui-goods-item {
  width: 100%;
  padding: 20rpx 30rpx;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
}

.tui-goods-img {
  width: 180rpx;
  height: 180rpx;
  display: block;
  flex-shrink: 0;
}

.tui-goods-center {
  flex: 1;
  padding: 20rpx 8rpx;
  box-sizing: border-box;
}

.tui-goods-name {
  max-width: 310rpx;
  word-break: break-all;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  font-size: 26rpx;
  line-height: 32rpx;
}

.tui-goods-attr {
  font-size: 22rpx;
  color: #888888;
  line-height: 32rpx;
  padding-top: 20rpx;
  word-break: break-all;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
}

.tui-price-right {
  text-align: right;
  font-size: 24rpx;
  color: #888888;
  line-height: 30rpx;
  padding-top: 20rpx;
}

.tui-color-red {
  color: #e41f19;
  padding-right: 30rpx;
}

.tui-goods-price {
  width: 100%;
  display: flex;
  align-items: flex-end;
  justify-content: flex-end;
  font-size: 24rpx;
}

.delivery-name,
.delivery-no {
  font-size: 28rpx;
  color: #888;
}

.delivery-no {
  padding-top: 10rpx;
}

.tui-size-24 {
  font-size: 24rpx;
  line-height: 24rpx;
}

.tui-price-large {
  font-size: 32rpx;
  line-height: 30rpx;
  font-weight: 500;
}

.tui-order-btn {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  background: #fff;
  padding: 10rpx 30rpx 20rpx;
  box-sizing: border-box;
}

.tui-btn-ml {
  margin-left: 20rpx;
}
</style>
